package com.jingdianjichi.club.getway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.nacos.common.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jingdianjichi.club.getway.entity.AuthPermission;
import com.jingdianjichi.club.getway.entity.AuthRole;
import com.jingdianjichi.club.getway.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限接口扩展
 * @author 86156
 * @version 1.0
 * @date 2024-10-30 13:56
 */
@Component
@Slf4j
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private RedisUtil redisUtil;
    
    private String authPermissionPrefix = "auth.permission";

    private String authRolePrefix = "auth.role";

    /**
     * @param loginId 账号id
     * @param loginType 账号类型
     * @return 返回此loginId所拥有的权限列表
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        /*
        * 1.直接跟数据库做交互
        * 2.redis缓存 推荐
        * 3.redis缓存没有的话,去调用我们的微服务去获取
        * */
        return getAuth(loginId.toString(),authPermissionPrefix);
    }

    /**
     * @param loginId 账号id
     * @param loginType 账号类型
     * @return 返回此loginId所拥有的角色列表
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getAuth(loginId.toString(),authRolePrefix);
    }

    private List<String> getAuth(String loginId,String authPrefix){
        log.info("loginId:{},authPrefix:{}",loginId,authPrefix);
        String authKey = redisUtil.buildKey(authPrefix, loginId);
        String authValue = redisUtil.get(authKey);
        if(StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }
        List<String> authList = new LinkedList<>();
        if(authRolePrefix.equals(authPrefix)){
            List<AuthRole> roleList = new Gson().fromJson(authValue, new TypeToken<List<AuthRole>>() {
            }.getType());
            authList = roleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());
        }else if(authPermissionPrefix.equals(authPrefix)){
            List<AuthPermission> roleList = new Gson().fromJson(authValue, new TypeToken<List<AuthPermission>>() {
            }.getType());
            authList = roleList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        }
        return authList;
    }

}
